<template>
	<view class="wanl-list">
		
		<!-- 导航条 -->
		<view class="cu-custom" :style="{height: $wanlshop.wanlsys().height + 'px' }">
			<view class="cu-bar bg-bgcolor fixed" :style="{ height: $wanlshop.wanlsys().height + 'px', paddingTop: $wanlshop.wanlsys().top + 'px'}">
				
				<view class="search-form round">
					<text class="wlIcon-sousuo1 text-bold"></text> 
					<input @confirm="confirm" :adjust-position="false" type="text" placeholder="搜索商家" confirm-type="search"></input>
				</view>
			</view>
		</view>
			
		<!-- <view class="head" :class="{ headtop: scrollStype }" style="margin-top: -15rpx;">
			<view class="cue">
				<view class="bar bar-list">
					<view class="item">同城商家</view>
				</view>
			</view>
		</view> -->
		<view class="swiper-box" v-if="bannersList.length > 0">
			<swiper class="swiper" circular :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
				:duration="duration">
				<swiper-item v-for="(item, index) in bannersList" :key="index">
					<image :src="'https://adminshop.12sxb.cn'+item.url" mode="aspectFill" style="width: 100%;"></image>
				</swiper-item>
			</swiper>
		</view>
		
		<view class="notice-wrapper margin-top-sm">
		    <swiper class="notice-swiper" circular="true" vertical="true" autoplay="true" interval="3000">
		      <swiper-item v-for="(item, index) in noticeList" :key="index">				  
				<!-- <uni-notice-bar show-icon :text="item"/> -->
				<view class="wanlpage-notice" style="background-color: rgb(255, 251, 232);color: rgb(222, 143, 28);padding: 4rpx 25rpx;">
					<text class="wlIcon wlIcon-notice margin-right-xs"></text>
					<text>{{item}}</text>
				</view>
		      </swiper-item>
		    </swiper>
		</view>
		
		<view class="padding-bj margin-sm bg-white" style="padding:10rpx 0">
			<view class="list text-sm flex justify-start" style="flex-flow:row wrap; badding:0;">
				
				<swiper @change="swchange" style="width:100%;height:420rpx">
						<swiper-item  v-for="(item,index) in subbussinfo" :key = "index" style="padding-bottom:20rpx !important">
							<view style="width:100%;height:100%;display:flex;justify-content: flex-start;align-items: flex-start; flex-flow:row wrap;">
								<view class="" v-for="it in item" style="text-align: center; width:20% "  :key="it.id">
									<view @click="getType(it.id)">
										<image :src="'https://adminshop.12sxb.cn'+it.img" style="width: 80rpx;height: 80rpx"></image>
										<view class="" :class="params.type === it.id ? 'text-orange' : ''">{{it.name}}</view>
									</view>						
								</view>
							</view>	
						</swiper-item>
				</swiper>
				
				<view class="dotwrpper">
					
					
					<view class="dot" :class="index == cindex?'act':''" v-for="(item,index) in subbussinfo" :key="index"></view>
				</view>
			
<!-- 				<view class="" style="text-align: center;">
					<view @click="getType(2)">
						<image src="/static/images/business/waimai.png" style="width: 60rpx;height: 60rpx"></image>
						<view class="" :class="params.type === 2 ? 'text-orange' : ''">外卖</view>	
					</view>	
				</view>
				<view class="" style="text-align: center;">
					<view  @click="getType(3)">
						<image src="/static/images/business/tianpin.png" style="width: 60rpx;height: 60rpx"></image>
						<view class="" :class="params.type === 3 ? 'text-orange' : ''">甜品饮料</view>	
					</view>	
				</view>
				<view class="" style="text-align: center;">
					<view  @click="getType(4)">
						<image src="/static/images/business/yule.png" style="width: 60rpx;height: 60rpx"></image>
						<view class="" :class="params.type === 4 ? 'text-orange' : ''">休闲娱乐</view>	
					</view>	
				</view> -->
			</view>
		</view>
<!-- 		<view v-for="(item, index) in common.modulesData.homeModules.item" :key="index">			
			<wanl-page-groups v-if="item.type == 'groups'" :pageData="item" :shopData="shopDataObj"/>
		</view> -->

		<view class="operate margin-bottom-xs">
			<view class="text-sm" @tap="getOrderType(1)">
				<text class="" style="padding:10rpx 60rpx" :class="params.orderType === 1 ? 'bg-orange' : 'bg-white'">推荐</text>
			</view>
			<view class="text-sm" @tap="getOrderType(2)">
				<text class="" style="padding:10rpx 60rpx" :class="params.orderType === 2 ? 'bg-orange' : 'bg-white'">附近</text>		
			</view>			
		</view>
		
		<!-- 主体 -->
		<block v-if="shopData.length > 0">
			<wanl-business :dataList="shopData" :dataStyle="liststyle"/>
		</block>
		<block v-if="shopData.length === 0 && status !== 'loading'">
			<wanl-empty :text="empty"/>
		</block>
		<uni-load-more :status="status" :content-text="contentText" />
		<view class="edgeInsetBottom"></view>
	</view>
</template>

<script>
	import { mapState } from 'vuex';
	export default {
		computed: {
			...mapState(['common','user'])
		},
		data() {
			return {
				cindex:0,
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				bannersList:[],
				noticeList: [],
				bussinfoList:[],
				subbussinfo:[],
				
				empty: '附近暂无商家~',
				WanlScroll: 0, //记录页面滚动
				scrollStype: false, //滚动状态
				priceOrder: 0, //1 价格从低到高 2价格从高到低
				liststyle: 'col-2-10', //列表样式
				shopData: [], //店铺列表数据
				shopDataObj:{},
				params: {
					search: '',
					type:'', //1美食 2外卖 3甜品饮料 4休闲娱乐
					orderType:1,//1推荐 2距离
					longitude: '',
					latitude: '',
					province:"",
					city:"",
					area:'',
					page: 1,
				},
				reload: false, //判断是否上拉
				last_page: 0,
				status: 'loading',
				contentText: {
					contentdown: '',
					contentrefresh: '正在加载..',
					contentnomore: ''
				},
				pagesNum: 0,
			
			}
		},
		onShow() {
			this.getAddress()
		},
		async onLoad() {
			this.getAddress();
			this.getBussinfoList();
			
	
			if(Object.keys(this.$store.state.common.addressData).length > 0){
				this.reload = true;
				this.loadData();
			}else if(uni.getStorageSync('addressData')){
				this.reload = true;
				this.loadData();
			}else{
				uni.showToast({
					title:'位置获取失败',
					icon:'error'
				})
				this.status = 'noMore';
				this.empty = '请重新获取定位~'
			}
			await this.getBanners();
			this.getNotices();
		},
	

		// 监听下拉刷新
		onPullDownRefresh() {
			if(Object.keys(this.$store.state.common.addressData).length > 0){
				this.params.page  = 1;
				this.reload = true;
				this.loadData();
			} else{
				uni.stopPullDownRefresh()
				uni.showToast({
					title:'位置获取失败',
					icon:'error'
				})
				this.status = 'noMore';
				this.empty = '请重新获取定位~'
			}								
		},
		// 上拉加载
		onReachBottom() {

			if(this.shopData.length == 0){
				this.contentText.contentdown = '我是有底线的';
				return ;
			}
			
			if (this.params.page > this.last_page) {
				this.status = 'noMore';
			} else {
				this.reload = false;
				if(this.params.page == this.last_page){
					this.contentText.contentdown = '我是有底线的';
				}else{
					this.contentText.contentdown = '上拉显示更多';
				}
				
				this.params.page = this.params.page + 1; //页码+1
				this.status = 'loading';
				this.loadData();
			}
		},
		// 监听滚动
		onPageScroll(object) {
			if (object.scrollTop > this.WanlScroll) {
				this.scrollStype = false;
			} else {
				this.scrollStype = true;
			}
			if (object.scrollTop < 0) {
				this.scrollStype = false;
			}
			this.WanlScroll = object.scrollTop;
		},
		methods: {
			
			swchange(e){
				console.log(e);
				console.log(e.detail.current);
				this.cindex = e.detail.current;
				console.log(this.cindex);
			},
			
			
			getBussinfoList(){
				uni.request({
					url: '/wanlshop/bussinfo/getBussinfoList',
					success:(res)=>{
						if(res.res.code == 1){
							this.bussinfoList = res.res.data;
							console.log(this.bussinfoList);
							
							this.subbussinfo = this.group(this.bussinfoList,15);
							console.log(this.subbussinfo);
							
						}
					}
				})
			},
			
			group(array, subGroupLength) {
			      let index = 0;
			      let newArray = [];
			      while(index < array.length) {
			          newArray.push(array.slice(index, index += subGroupLength));
			      }
			      return newArray;
			  },
			
			
			
			
			//获取轮播图
			getBanners(){
				uni.request({
					url: '/common/banners?type=2',
					success: res => {
						this.bannersList = res.data
					}
				});
			},
			//获取公告
			getNotices(){
				uni.request({
					url: '/wanlshop/shop/notices',
					success: res => {
						this.noticeList = res.data
					}
				});
			},
			
			//异步加载商家列表        
			async loadData() {
				console.log("*************")
				let _addressData = uni.getStorageSync('addressData');/*全局缓存相关的数据*/
				if(_addressData){
					let addressData = JSON.parse(_addressData);
						if(addressData.province)this.params.province = addressData.province;
						if(addressData.city)this.params.city = addressData.city;
						if(addressData.district)this.params.area = addressData.district;  
						if(addressData.longitude){this.params.longitude = addressData.longitude;}
						if(addressData.latitude){this.params.latitude = addressData.latitude;}
				}
				
				
				await uni.request({
					url: '/wanlshop/shop/getShopList',
					data: this.params,
					success: res => { 
						console.log("res=" + JSON.stringify(res));
						uni.stopPullDownRefresh(); // 后来统一补充，尚不知道是否有效在此处
						this.status = res.data.total == 0 ? 'noMore':'more';
						//////////////////////////////////////////////////////////////
						let _data = res.data.data;
						let _data2 = new Array();
						if(_data){
							for(var i = 0; i < _data.length; i++) {
								if(_data[i]['count'] >0){
									 _data2.push(_data[i]);
								}
							} 
						}
						console.log("_data2=" + JSON.stringify(_data2));
						res.data.data = _data2;
						
						
						////////////////////////////////////////////////////////////////
						this.shopData = this.reload ? res.data.data : this.shopData.concat(res.data.data); //数据 追加
						this.shopData.map((item,index)=>{
							item.newDistance = this.calculateDistance(item.latitude, item.longitude)						
						})
						this.shopDataObj = this.shopData.filter(o=>o.user_id == this.$store.state.user.id)
						this.shopDataObj = this.shopDataObj[0]
						this.params.page = res.data.current_page; //当前页码
						this.last_page = res.data.last_page; //总页码
					}
				});
			},
			
			//根据经纬度计算距离
			 calculateDistance(e1,e2) {
				 let location1 ={
					 lat:this.params.latitude,
					 lng:this.params.longitude
				 }
				 let location2 = { lat:e1, lng:e2}
				 console.log(location1)
				  console.log(location2)
			      const { lat: lat1, lng: lng1 } = location1;
			      const { lat: lat2, lng: lng2 } = location2;
			 
			      const rad = (deg) => (deg * Math.PI) / 180;
			      const R = 6371; // 地球半径，单位为公里
			 
			      const latitude = rad(lat2 - lat1);
			      const longitude = rad(lng2 - lng1);
			 
			      const lat1Rad = rad(lat1);
			      const lat2Rad = rad(lat2);
			 
			      const a = Math.sin(latitude / 2) * Math.sin(latitude / 2) +
			                Math.cos(lat1Rad) * Math.cos(lat2Rad) *
			                Math.sin(longitude / 2) * Math.sin(longitude / 2);
			      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
			 
				 return  R * c  * 1000;
				 
			},
		
			// editListstyle() {
			// 	if (this.liststyle == 'col-1-10') {
			// 		this.liststyle = 'col-2-10';
			// 	} else {
			// 		this.liststyle = 'col-1-10';
			// 	}
			// },
			
			//分类筛选
			getType(type) {
				this.params.type = type
				this.reload = true;
				this.loadData();
			},	
			//推荐 附近
			getOrderType(orderType){
				this.params.orderType = orderType;
				this.reload = true;
				this.params.page = 1;
				this.loadData();
			},
			//搜索
			confirm(event){
				this.params.search = event.detail.value;
				this.reload = true;
				this.loadData();
				
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				});
			},
			
			getAddress(){
				let res = this.$store.state.common.addressData
				if(Object.keys(res).length !== 0){					
					this.params.longitude = res.longitude
					this.params.latitude = res.latitude
					
					let _addressData = uni.getStorageSync('addressData');/*全局缓存相关的数据*/
					if(_addressData){
						let addressData = JSON.parse(_addressData); 
						if(addressData.province)this.params.province = addressData.province;
						if(addressData.city)this.params.city = addressData.city;
						if(addressData.district)this.params.area = addressData.district;  
					}else{
						this.params.province = res.address.province
						this.params.city = res.address.city
						this.params.area = res.address.district
					}
					
					
				}		
			}
		
		}
	};
</script>

<style lang="scss" scoped>
	::v-deep .empty-content{
		padding: 0;
	}
	.notice-wrapper {
	  height: 46rpx; /* 通告栏的高度 */
	  overflow: hidden;
	}
	.notice-swiper {
	  height: 100%; /* 设置swiper的高度为外层容器的高度 */
	}

	.swiper-box uni-image{
		width: 100%;
		height: 180px;
	}
	.swiper-box swiper{
		height: 180px;
	}
	
	.itemtag{
		width:140rpx;
		height:140rpx;
	}
	
	.cu-bar .search-form{
		background-color: #ebebeb;
	}
	.bar-list{
		justify-content: center !important;
	}
	
		/* 滑动列表 */
	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}
	.scroll-view-item_H {
		display: inline-block;
		width: 170rpx;
	}
	
	.dotwrpper{
		width:100%;
		display: flex;
		justify-content: center;
		align-items: center;
		.dot{
			width:40rpx;
			height:5rpx;
			background:#aaa;
			margin-right:20rpx;
		}
		.act{
			background:#333;
		}
	}
	
	
	/* 操作 */
	.operate {
		display: flex;
		justify-content: space-around;
		text-align: center;
	}
	
	.uni-swiper-dot{
		bottom:30px;
	}
	
	.operate text {
		display: block;
		font-size: 32rpx;
		padding-left: 100rpx;
		padding-right: 100rpx;
		border: 1rpx solid #dddddd;
	}
	
	.wanl-user-tool {
		background-color: #ffffff;
	}
	.wanl-user-tool .list {
		text-align: center;
	}	
	.wanl-user-tool .list text {
		display: block;
		font-size: 54rpx;
		margin-bottom: 8rpx;
	}
	
</style>
